<?php


namespace api\crm\controller;


use api\crm\model\ActivitySignModel;
use api\crm\model\GetCardLogModel;
use api\crm\model\GoodsModel;
use api\crm\model\GoodsSpecModel;
use api\crm\model\WechatUserAddressModel;
use api\crm\model\WechatUserModel;
use api\crm\model\WechatUserPointsLogModel;
use app\admin\logic\HookLogic;
use app\admin\model\AfterServiceModel;
use app\admin\model\ApplyRefundModel;
use app\admin\model\CouponModel;
use app\admin\model\OrderInfoModel;
use cmf\controller\RestBaseController;
use plugins\wechat\WechatPlugin;

class WechatUserController extends RestBaseController
{

    public function add_user_address()
    {
        $user_id = $this->getWechatUserId();
        $data = $this->request->param();
        $validate_result = $this->validate($data, 'UserAddress');
        if ($validate_result !== true) {
            $this->error($validate_result);
        } else {
            $data['user_id'] = $user_id;
            $is_default = isset($data['is_default']) && $data['is_default'] ? $data['is_default'] : 0;
            if ($is_default == 1) {
                $list = WechatUserAddressModel::where('user_id', $user_id)->all();
                if ($list) {
                    WechatUserAddressModel::where('user_id', $user_id)->update(['is_default' => 0]);
                }
            }
            $model = WechatUserAddressModel::create($data);
            $res = $model->save();
            if ($res) {
                $this->success('新增成功');
            } else {
                $this->error('新增失败');
            }
        }
    }

    public function edit_user_address()
    {
        $data = $this->request->param();
        $user_id = $this->getWechatUserId();
        $validate_result = $this->validate($data, 'UserAddress');
        if ($validate_result !== true) {
            $this->error($validate_result);
        }
        $id = isset($data['id']) && $data['id'] ? intval($data['id']) : 0;
        $address_info = WechatUserAddressModel::where(['user_id' => $user_id, 'id' => $id])->find();
        if (empty($address_info)) {
            $this->error('地址不存在或已被删除');
        } else {
            $is_default = isset($data['is_default']) && $data['is_default'] ? $data['is_default'] : 0;
            if ($is_default == 1) {
                $list = WechatUserAddressModel::where('user_id', $user_id)->all();
                if ($list) {
                    WechatUserAddressModel::where('user_id', $user_id)->update(['is_default' => 0]);
                }
            }
            $address_info->is_default = $is_default;
            $address_info->province = $data['province'];
            $address_info->city = $data['city'];
            $address_info->area = $data['area'];
            $address_info->address = $data['address'];
            $address_info->mobile = $data['mobile'];
            $address_info->name = $data['name'];
            $res = $address_info->save();
            if ($res) {
                $this->success('修改成功');
            } else {
                $this->error('修改失败');
            }
        }
    }

    public function get_user_address_detail()
    {
        $data = $this->request->param();
        $user_id = $this->getWechatUserId();
        $id = isset($data['id']) && $data['id'] ? intval($data['id']) : 0;
        $address_info = WechatUserAddressModel::where(['user_id' => $user_id, 'id' => $id])->find();
        if (empty($address_info)) {
            $this->error('地址不存在或已被删除');
        } else {
            $this->success('获取地址详细信息', $address_info);
        }
    }

    public function set_user_default_address()
    {
        $user_id = $this->getWechatUserId();
        $data = $this->request->param();
        $id = isset($data['id']) && $data['id'] ? $data['id'] : 1;
        $model = WechatUserAddressModel::where(['id' => $id, 'user_id' => $user_id])->find();
        if ($model) {
            $list = WechatUserAddressModel::where('user_id', $user_id)->all();
            if ($list) {
                WechatUserAddressModel::where('user_id', $user_id)->update(['is_default' => 0]);
            }
            $model->is_default = 1;
            $res = $model->save();
            if ($res) {
                $this->success('设置成功');
            } else {
                $this->error('设置失败');
            }
        } else {
            $this->error('数据异常');
        }
    }

    public function delete_user_address()
    {
        $user_id = $this->getWechatUserId();
        $data = $this->request->param();
        $id = isset($data['id']) && $data['id'] ? $data['id'] : 0;
        $info = WechatUserAddressModel::where('user_id', $user_id)->get($id);
        if ($info) {
            $res = $info->delete();
            if ($res) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('地址不存在或已被删除');
        }
    }

    // 获取微信用户信息
    public function get_wechat_user_info()
    {
        $user_id = $this->getWechatUserId();
        $user_info = WechatUserModel::get($user_id);
        $company_id = $user_info['company_id'];
        $card_ids = CouponModel::when('company_id', $company_id)->column('card_id');
        $user_info['coupon_count'] = GetCardLogModel::where('card_id', 'in', $card_ids)->where(['status' => 0, 'openid' => $user_info['openid']])->count();
        $user_info['activity_count'] = ActivitySignModel::where(['user_id' => $user_id, 'status' => 1])->count();
        $user_info['need_pay_order_count'] = OrderInfoModel::where([
            'user_id' => $user_id, 'order_status' => 0, 'pay_status' => 1, 'shipping_status' => 0])->count();
        $user_info['need_shipping_order_count'] = OrderInfoModel::where([
            'user_id' => $user_id, 'order_status' => 0, 'pay_status' => 2, 'shipping_status' => 0])->count();
        $user_info['need_receive_order_count'] = OrderInfoModel::where([
            'user_id' => $user_id, 'order_status' => 0, 'pay_status' => 2, 'shipping_status' => 1])->count();
        $user_info['finish_order_count'] = OrderInfoModel::where([
            'user_id' => $user_id, 'order_status' => 0, 'pay_status' => 2, 'shipping_status' => 3])->count();
        $this->success('获取微信用户信息', $user_info);
    }

    public function get_user_address()
    {
        $user_id = $this->getWechatUserId();
        $address_list = WechatUserAddressModel::where('user_id', $user_id)
            ->order('is_default desc,create_time desc')->all();
        $this->success('获取用户地址列表', $address_list);
    }

    public function get_user_order_list()
    {
        $data = $this->request->param();
        $page = isset($data['page']) && $data['page'] ? $data['page'] : 1;
        $num = 10;
        $where = [];
        $status = isset($data['status']) && $data['status'] ? $data['status'] : 0;
        $user_id = $this->getWechatUserId();
        $where[] = ['user_id', '=', $user_id];
        $where[] = ['is_delete', '=', 0];
        switch ($status) {
            case 100:
                //待支付
                $where[] = ['order_status', '=', 0];
                $where[] = ['pay_status', '=', 1];
                $where[] = ['shipping_status', '=', 0];
                break;
            case 101:
                //待发货
                $where[] = ['order_status', '=', 0];
                $where[] = ['pay_status', '=', 2];
                $where[] = ['shipping_status', '=', 0];
                break;
            case 102:
                //待收货
                $where[] = ['order_status', '=', 0];
                $where[] = ['pay_status', '=', 2];
                $where[] = ['shipping_status', '=', 1];
                break;
            case 103:
                //已完成
                $where[] = ['order_status', '=', 0];
                $where[] = ['pay_status', '=', 2];
                $where[] = ['shipping_status', '=', 3];
                break;
            default:
                $where[] = ['pay_status', '<>', 0];
                break;
        }
        $order_list = OrderInfoModel::with(['order_goods_list' => ['goods_info', 'goods_spec'], 'coupon_info'])
            ->where($where)
            ->order('create_time desc')
            ->paginate($num, false, ['page' => $page])
            ->each(function ($item) {
                if ($item['create_time']) {
                    $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                }
                if ($item['pay_time']) {
                    $item['pay_time'] = date('Y-m-d H:i:s', $item['pay_time']);
                }
                if ($item['shipping_time']) {
                    $item['shipping_time'] = date('Y-m-d H:i:s', $item['shipping_time']);
                }
                $list = $item['order_goods_list'];
                if ($list) {
                    foreach ($list as $key => $value) {
                        $img = $value['img'];
                        if ($img) {
                            $array = explode(',', $img);
                            $temp_array = [];
                            foreach ($array as $value) {
                                $temp_array[] = $this->request->domain() . $value;
                            }
                            $list[$key]['img'] = $temp_array;
                        }
                    }
                    $item['count'] = count($list);
                }
                $item['order_goods_list'] = $list;
                return $item;
            });
        $this->success('我的订单列表', $order_list);
    }

    public function get_user_order_detail()
    {
        $data = $this->request->param();
        $user_id = $this->getWechatUserId();
        $order_sn = isset($data['order_sn']) && $data['order_sn'] ? $data['order_sn'] : '';
        $order_info = OrderInfoModel::with(['order_goods_list' => ['goods_info', 'goods_spec'], 'coupon_info', 'refund_info'])
            ->where(['user_id' => $user_id, 'order_sn' => $order_sn])->find();
        if (empty($order_info)) {
            $this->error('订单不存在');
        }
        foreach ($order_info['order_goods_list'] as $key => $value) {
            $img = $value['img'];
            if ($img) {
                $array = explode(',', $img);
                $temp_array = [];
                foreach ($array as $value) {
                    $temp_array[] = $this->request->domain() . $value;
                }
                $order_info['order_goods_list'][$key]['img'] = $temp_array;
            }

        }
        if ($order_info['create_time']) {
            $order_info['create_time'] = date('Y-m-d H:i:s', $order_info['create_time']);
        }
        if ($order_info['pay_time']) {
            $order_info['pay_time'] = date('Y-m-d H:i:s', $order_info['pay_time']);
        }
        if ($order_info['shipping_time']) {
            $order_info['shipping_time'] = date('Y-m-d H:i:s', $order_info['shipping_time']);
        }
        if ($order_info['finish_time']) {
            $order_info['finish_time'] = date('Y-m-d H:i:s', $order_info['finish_time']);
        }
        if ($order_info['refund_time']) {
            $order_info['refund_time'] = date('Y-m-d H:i:s', $order_info['refund_time']);
        }
        $this->success('订单详细', $order_info);
    }

    public function apply_refund_order()
    {
        $data = $this->request->param();
        $order_sn = isset($data['order_sn']) && $data['order_sn'] ? $data['order_sn'] : '';
        $reason = isset($data['reason']) && $data['reason'] ? $data['reason'] : '';
        $money = isset($data['money']) && $data['money'] ? $data['money'] : 0;
        $user_id = $this->getWechatUserId();
        $user_info = WechatUserModel::get($user_id);
        $order_info = OrderInfoModel::with('order_goods_list')->where(['order_sn' => $order_sn, 'is_delete' => 0, 'user_id' => $user_id])->find();
        if (empty($order_info)) {
            $this->error('订单信息不存在');
        }
        if ($order_info['order_status'] == '确认订单' && $order_info['pay_status'] == '已支付') {
            if ($order_info['shipping_status'] == '未发货') {
                $refund_order_sn = "REFUND_" . cmf_get_order_sn();
                $order_info->refund_money = $order_info['money_paid'];
                $order_info->refund_reason = '订单未发货全额退款';
                $order_info->refund_order_sn = $refund_order_sn;
                $order_info->refund_time = time();

                if ($order_info['money_paid'] > 0) {
                    $param['company_id'] = $order_info['company_id'];
                    $param['order_sn'] = $order_info['pay_sn'];
                    $param['total_money'] = $order_info['money_paid'] * 100;
                    $param['refund_money'] = $order_info['money_paid'] * 100;
                    $param['refund_order_sn'] = $refund_order_sn;
                    $param['desc'] = '订单未发货全额退款';
                    $res = hook('wechat_web_refund', $param);
                    if ($res[0]['return_code'] == 'SUCCESS' && $res[0]['return_msg'] == 'OK' && $res[0]['result_code'] == 'SUCCESS') {
                        $order_info->order_status = 2;
                        $order_info->pay_status = 3;
                        $order_info->save();
                        if ($order_info['pay_points'] > 0) {
                            $add_log = new WechatUserPointsLogModel([
                                'user_id' => $user_id,
                                'change_points' => $order_info['pay_points'],
                                'before_points' => $user_info['points'],
                                'after_points' => $user_info['points'] + $order_info['pay_points'],
                                'order_sn' => $order_sn,
                                'remark' => '订单号' . $order_sn . '退回' . $order_info['pay_points'] . '积分'
                            ]);
                            $add_log->save();
                            $user_info->points = ['inc', $order_info['pay_points']];
                            $user_info->save();


                            // 变更 会员卡 积分
                            $card_info = \app\admin\model\GetCardLogModel::where('openid', $user_info['openid'])->find();
                            $obj = new WechatPlugin();

                            $obj->update_card_info([
                                'company_id' => $user_info['company_id'],
                                'user_id'    => $user_info['id'],
                                'cardId'     => $card_info['card_id'],
                                'code'       => $card_info['user_card_code'],
                                'bonus'      => $user_info['points'] + $order_info['pay_points'],
                            ]);


                        }
                        $order_goods_list = $order_info['order_goods_list'];
                        foreach ($order_goods_list as $key => $value) {
                            $goods_info = GoodsModel::get($value['goods_id']);
                            $goods_info->stock = ['inc', $value['num']];
                            $goods_info->save();
                            if ($value['spec_id']) {
                                $spec_info = GoodsSpecModel::get($value['spec_id']);
                                $spec_info->stock = ['inc', $value['num']];
                                $spec_info->save();
                            }
                        }
                        $this->success('退款成功');
                    } else {
                        $this->error('退款失败');
                    }
                } else {
                    if ($order_info['pay_points'] > 0) {
                        $add_log = new WechatUserPointsLogModel([
                            'user_id' => $user_id,
                            'change_points' => $order_info['pay_points'],
                            'before_points' => $user_info['points'],
                            'after_points' => $user_info['points'] + $order_info['pay_points'],
                            'order_sn' => $order_sn,
                            'remark' => '订单号' . $order_sn . '退回' . $order_info['pay_points'] . '积分'
                        ]);
                        $add_log->save();
                        $user_info->points = ['inc', $order_info['pay_points']];
                        $user_info->save();
                    }
                    $order_info->order_status = 2;
                    $order_info->pay_status = 3;
                    $order_info->save();
                    $order_goods_list = $order_info['order_goods_list'];
                    foreach ($order_goods_list as $key => $value) {
                        $goods_info = GoodsModel::get($value['goods_id']);
                        $goods_info->stock = ['inc', $value['num']];
                        $goods_info->save();
                        if ($value['spec_id']) {
                            $spec_info = GoodsSpecModel::get($value['spec_id']);
                            $spec_info->stock = ['inc', $value['num']];
                            $spec_info->save();
                        }
                    }
                    $this->success('退款成功');
                }
            } else {
                $refund_log = ApplyRefundModel::where(['user_id' => $user_id, 'order_sn' => $order_sn])->find();
                if ($refund_log) {
                    $this->error('请勿重复提交退款记录');
                }
                $refund_log = new ApplyRefundModel([
                    'user_id' => $user_id,
                    'order_sn' => $order_sn,
                    'reason' => $reason,
                    'money' => $money
                ]);
                $order_info->order_status = 2;
                $order_info->save();
                $res = $refund_log->save();
                if ($res) {
                    $this->success('申请退款成功');
                } else {
                    $this->error('申请退款失败');
                }
            }
        } else {
            $this->error('订单状态异常');
        }

    }

    /**
     * 完成订单
     */
    public function finish_order()
    {
        $data = $this->request->param();
        $user_id = $this->getWechatUserId();
        $order_sn = isset($data['order_sn']) && $data['order_sn'] ? $data['order_sn'] : '';
        $order_info = OrderInfoModel::where(['user_id' => $user_id, 'order_sn' => $order_sn])->find();
        if (empty($order_info)) {
            $this->error('订单不存在');
        }
        $user_info = WechatUserModel::get($user_id);
        if ($order_info['order_status'] == '确认订单' && $order_info['pay_status'] == '已支付' && $order_info['shipping_status'] == '已发货') {
            $order_info->shipping_status = 3;
            $order_info->finish_time = time();
            $res = $order_info->save();
            if ($order_info['gift_points'] > 0) {
                $add_log = new WechatUserPointsLogModel([
                    'user_id' => $order_info['user_id'],
                    'change_points' => $order_info['gift_points'],
                    'before_points' => $user_info['points'],
                    'after_points' => $user_info['points'] + $order_info['gift_points'],
                    'order_sn' => $order_sn,
                    'remark' => '订单号' . $order_sn . '赠送' . $order_info['gift_points'] . '积分'
                ]);
                $add_log->save();
                $user_info->points = ['inc', $order_info['gift_points']];
                $user_info->save();
            }
            if ($res) {
                $this->success('确认订单成功');
            } else {
                $this->error('确认订单失败');
            }
        } else {
            $this->error('订单状态异常');
        }
    }

    public function delete_order()
    {
        $data = $this->request->param();
        $user_id = $this->getWechatUserId();
        $order_sn = isset($data['order_sn']) && $data['order_sn'] ? $data['order_sn'] : '';
        $order_info = OrderInfoModel::where(['user_id' => $user_id, 'order_sn' => $order_sn])->find();
        if (empty($order_info)) {
            $this->error('订单不存在');
        }
        if (($order_info['order_status'] == '确认订单' && $order_info['pay_status'] == '已支付'
                && $order_info['shipping_status'] == '已收货') || $order_info['order_status'] == '取消订单' ||
            ($order_info['order_status'] == '退款订单' && $order_info['pay_status'] == '已退款')) {
            $order_info->is_delete = 1;
            $res = $order_info->save();
            if ($res) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        } else {
            $this->error('订单状态异常');
        }
    }

    public function add_after_sale_service()
    {
        $data = $this->request->param();
        $user_id = $this->getWechatUserId();
        $user_info = WechatUserModel::get($user_id);
        $order_sn = isset($data['order_sn']) && $data['order_sn'] ? $data['order_sn'] : '';
        $user_name = isset($data['user_name']) && $data['user_name'] ? $data['user_name'] : '';
        $mobile = isset($data['mobile']) && $data['mobile'] ? $data['mobile'] : '';
        $content = isset($data['content']) && $data['content'] ? $data['content'] : '';
        $type = isset($data['type']) && $data['type'] ? $data['type'] : 0;
        $model = new AfterServiceModel([
            'user_id' => $user_id,
            'company_id' => $user_info['company_id'],
            'order_sn' => $order_sn,
            'user_name' => $user_name,
            'mobile' => $mobile,
            'content' => $content,
            'type' => $type
        ]);
        $res = $model->save();
        if ($res) {
            $this->success('申请售后成功,请等待客服人员处理');
        } else {
            $this->error('申请失败');
        }
    }

    public function get_user_points_log()
    {
        $data = $this->request->param();
        $user_id = $this->getWechatUserId();
        $page = isset($data['page']) && $data['page'] ? $data['page'] : 1;
        $num = 10;
        $list = WechatUserPointsLogModel::where(['user_id' => $user_id])
            ->order('create_time desc')
            ->paginate($num, false, ['page' => $page])->each(function ($item) {
                if ($item['create_time']) {
                    $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                }
                return $item;
            });
        if ($list) {
            $list = $list->toArray();

            foreach ($list['data'] as $k =>$v) {
                if ($v['before_points'] > $v['after_points']) {
                    $list['data'][$k]['can'] = '-';
                } else {
                    $list['data'][$k]['can'] = '+';
                }
            }

            //dump($list->toArray());die;
        }


        $this->success('用户积分记录', $list);
    }

    public function refund_order()
    {
        $data = $this->request->param();

        $param['order_sn'] = $data['order_sn'];
        $param['total_money'] = $data['money'];
        $param['refund_money'] = $data['money'];
        $param['company_id'] = $data['id'];
        $param['desc'] = '活动退款';
        $res = hook('wechat_web_refund', $param);
        $this->success('退款成功', $res);
    }
}
